package com.aiatomic.couting;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.aiatomic.couting.models.OrderEntity;
import com.aiatomic.couting.util.AppUtils;
import com.aiatomic.couting.util.HttpUtils;
import com.aiatomic.couting.util.SystemUtil;
import com.alipay.sdk.app.PayTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

public class PayActivity extends Activity {
	private WebView webView;
	private String oid;
	private OrderEntity order;
	private int SDK_PAY_FLAG = 0;
	private CountDownTimer timer;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SDK_PAY_FLAG) {
				Map<String, String> result = (Map<String, String>) msg.obj;
				if (result.get("resultStatus").equals("9000") || result.get("resultStatus").equals("8000")
						|| result.get("resultStatus").equals("6004")) {
					AppUtils.refresh_currency(PayActivity.this);
				}
				PayActivity.this.finish();
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pay);
		TextView txtBack = (TextView) this.findViewById(R.id.txtBack);
		txtBack.setText(R.string.back);
		txtBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		TextView txtNext = (TextView) this.findViewById(R.id.txtNext);
		txtNext.setVisibility(View.INVISIBLE);

		TextView txtMiddle = (TextView) this.findViewById(R.id.txtMiddle);
		txtMiddle.setVisibility(View.VISIBLE);
		txtMiddle.setText(R.string.title_activity_pay);
		this.oid = this.getIntent().getStringExtra("oid");
		this.order = (OrderEntity) this.getIntent().getSerializableExtra("order");
		((TextView) this.findViewById(R.id.pay_product_name)).setText(this.getIntent().getStringExtra("name"));
		((TextView) this.findViewById(R.id.pay_product_desc)).setText(this.getIntent().getStringExtra("desc"));
		((TextView) this.findViewById(R.id.pay_product_real_price))
				.setText(this.getIntent().getStringExtra("real_price"));
		this.timer = new CountDownTimer((AppUtils.order_clean - 2) * 1000, 1000) {

			@Override
			public void onTick(long millisUntilFinished) {
				int leftTime = (int) ((order.getCreated_time_loc().getTime() + AppUtils.order_clean * 1000
						- Calendar.getInstance().getTimeInMillis()) / 1000);
				if(leftTime<2){
					finish();
				}
				((TextView) PayActivity.this.findViewById(R.id.txt_order_clean))
						.setText(String.format("订单支付将于%d分%d秒后超时关闭", leftTime / 60, leftTime % 60));

			}

			@Override
			public void onFinish() {
				finish();
			}
		};
		timer.start();

		bindEvent();
	}

	private void bindEvent() {
		this.findViewById(R.id.btn_pay).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AliaPay();
			}
		});
	}

	private void payView() {
		/*
		 * webView = (WebView) this.findViewById(R.id.webView); WebSettings
		 * settings = webView.getSettings();
		 * settings.setJavaScriptEnabled(true); String oid =
		 * this.getIntent().getStringExtra("oid"); Map<String, String> params =
		 * new HashMap<String, String>(); params.put("aid", AppUtils.aid);
		 * params.put("oid", oid); params.put("platform",
		 * String.valueOf(IConstant.PLATFORM)); params.put("time",
		 * String.valueOf(Calendar.getInstance().getTimeInMillis()));
		 * params.put("channel", String.valueOf(AppUtils.channel));
		 * params.put("sign", HttpUtils.md5(params.get("aid") +
		 * params.get("oid") + params.get("time") + params.get("platform") +
		 * params.get("channel") + IConstant.NORMAL_MD5_KEY));
		 * params.put("ssign", HttpUtils.md5(params.get("aid") +
		 * params.get("oid") + params.get("time") + params.get("platform") +
		 * params.get("channel") + AppUtils.sKey)); String postData = ""; for
		 * (String key : params.keySet()) { postData += (key + "=" +
		 * params.get(key) + "&"); } webView.postUrl(AppUtils.url +
		 * "/v/cRecharge/goPayView", EncodingUtils.getBytes(postData,
		 * "BASE64")); webView.setWebViewClient(new WebViewClient() {
		 * 
		 * @Override public boolean shouldOverrideUrlLoading(final WebView view,
		 * String url) { if (!(url.startsWith("http") ||
		 * url.startsWith("https"))) { return true; }
		 * 
		 * final PayTask task = new PayTask(PayActivity.this); boolean
		 * isIntercepted = task.payInterceptorWithUrl(url, true, new
		 * H5PayCallback() {
		 * 
		 * @Override public void onPayResult(final H5PayResultModel result) { //
		 * 支付结果返回 final String url = result.getReturnUrl(); if
		 * (!TextUtils.isEmpty(url)) { PayActivity.this.runOnUiThread(new
		 * Runnable() {
		 * 
		 * @Override public void run() { view.loadUrl(url); } }); } } });
		 * 
		 * if (!isIntercepted) { view.loadUrl(url); } return true; } });
		 */
	}

	private void AliaPay() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("platform", String.valueOf(IConstant.PLATFORM));
		params.put("pay_type", "1");
		params.put("aid", AppUtils.aid);
		params.put("oid", oid);
		params.put("client_version", SystemUtil.getAppVersion(this));
		params.put("time", String.valueOf(Calendar.getInstance().getTimeInMillis()));
		params.put("channel", String.valueOf(AppUtils.channel));
		params.put("sign", HttpUtils.md5(params.get("aid") + params.get("time") + params.get("client_version")
				+ params.get("platform") + params.get("channel") + IConstant.NORMAL_MD5_KEY));
		params.put("ssign", HttpUtils.md5(params.get("aid") + params.get("time") + params.get("client_version")
				+ params.get("platform") + params.get("channel") + AppUtils.sKey));
		HttpUtils.post(new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == HttpUtils.CODE_SUCCESS_RQ_100) {
					final String orderInfo = msg.obj.toString();
					Runnable payRunnable = new Runnable() {

						@Override
						public void run() {
							PayTask alipay = new PayTask(PayActivity.this);
							Map<String, String> result = alipay.payV2(orderInfo, true);
							Message msg = new Message();
							msg.what = SDK_PAY_FLAG;
							msg.obj = result;
							mHandler.sendMessage(msg);
						}
					};
					// 必须异步调用
					Thread payThread = new Thread(payRunnable);
					payThread.start();
				} else {
					Toast toast = Toast.makeText(PayActivity.this, ICodeMsg.ERROR_CODES_HTTP.get(msg.what),
							Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
			}

		}, AppUtils.url + "/v/cRecharge/pay", params);
	}

}
